package 简单.二叉搜索树中的众数;

import java.util.ArrayList;

public class Solution1 {
    ArrayList<Integer> answer = new ArrayList<>();
    int base;
    int count;
    int maxcount;

    public int[] findMode(TreeNode root) {
        dfs(root);
        int[] mode =  new int[answer.size()];
        for (int i = 0; i < answer.size(); i++) {
            mode[i] = answer.get(i);
        }
        return mode;
    }

    public void dfs(TreeNode o){
        if(o==null) return;

        dfs(o.left);
        update(o.val);
        dfs(o.right);
    }

    public void update(int val){
        if(val == base){
            count++;
        }else{
            base = val;
            count = 1;
        }

        if(count == maxcount){
            answer.add(base);
        }

        if(count > maxcount){
            maxcount = count;
            answer.clear();
            answer.add(base);
        }
    }

}
